package com.tang.framework.component;

import com.tang.common.exception.eumes.Error;
import com.tang.common.model.LabelValue;
import com.tang.framework.core.domain.HttpResult;
import com.tang.common.exception.BusinessException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author tang jun liang
 * @Date 2023/4/24 11:55
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public HttpResult<String> businessException(BusinessException e)
    {
        return HttpResult.error(e.getErrorCodeMessage());
    }

    @ExceptionHandler(Exception.class)
    public HttpResult<String> exception(Exception e) {
        e.printStackTrace();
        return HttpResult.error("操作异常");
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HttpResult<List<LabelValue<String>>> handleError(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        List<LabelValue<String>> labelValueList = fieldErrorList.stream().map(item -> {
            LabelValue<String> labelValue = new LabelValue<>();
            labelValue.setLabel(item.getField());
            labelValue.setValue(item.getDefaultMessage());
            return labelValue;
        }).collect(Collectors.toList());
        return HttpResult.error(Error.ARGUMENT_ERROR, labelValueList);

    }
}
